// pages/courseComment/courseComment.js
import {
  request,
  upload
} from '../../utils/util.js'

Page({

  /**
   * 页面的初始数据
   */
  data: {
    score: 0, //评分
    imageList: [],
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    this.setData({
      teacher_id: options.teacher_id,
      course_book_id: options.id
    })
  },

  changeScore: function(e) {
    let index = e.currentTarget.dataset.index;
    this.setData({
      score: index
    })
  },

  input: function(e) {
    let value = e.detail.value;
    this.setData({
      comment: value
    })
  },

  //获取评论列表
  addComment: function() {
    let that = this;

    let {
      score,
      comment,
      imageList
    } = this.data;

    let data = {
      teacher_id: that.data.teacher_id,
      course_book_id: that.data.course_book_id
    }

    if (score < 1) {
      wx.showToast({
        title: '请先为该课时打分',
        icon: 'none',
      })
      return;
    }
    data.score = score;

    if (!comment || comment.length < 1) {
      wx.showToast({
        title: '请填写评论内容',
        icon: 'none',
      })
      return;
    }
    data.comment = comment;

    data.images = imageList;

    request({
      url: 'Comment/addCommentUser',
      data: data,
      method: 'POST',
      success: data => {
        wx.showModal({
          title: '温馨提示',
          content: '评价成功',
          showCancel: false,
          success: function(res) {
            wx.navigateBack()
          },
        })
      },
    })
  },

  //上传图片
  uploadImage: function() {
    let that = this;

    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      success: res => {
        const tempFilePaths = res.tempFilePaths
        upload({
          url: 'Home/upload', // 
          filePath: tempFilePaths[0],
          name: 'file',
          success: data => {
            console.log(data)
            that.setData({ imageList: [...that.data.imageList, data]})
          }
        })
      }
    })
  },

  //删除图片
  deleteImg: function(e) {
    let {index} = e.currentTarget.dataset;
    let imageList = this.data.imageList;
    imageList.splice(index, 1);
    this.setData({
      imageList
    })
  },
})